import React, { useEffect, useState, useContext } from "react";
import { autorun } from "mobx";
import { Observer } from "mobx-react-lite";
import { useRouteMatch, useLocation, useHistory } from "react-router";
import { DockedAppContainer, Workbench } from "@anyshare/components";
import { useAppContainerManager, useLanguage, useEventBus } from "@anyshare/common/lib/hooks";
import { Upload } from "@anyshare/migrate";
import { HandleActivityContext } from "@anyshare/common/lib/contexts";

export default function AppPage() {
    const appContainerManager = useAppContainerManager();
    const activityContext = useContext(HandleActivityContext);
    const {
        params: { app, slash },
    } = useRouteMatch<{ app: string; slash: string }>();
    const { search } = useLocation();
    const history = useHistory();
    const language = useLanguage();
    const eventBus = useEventBus();
    const [dropState, setDropState] = useState(true);

    useEffect(() => {
        appContainerManager.start(`${app}/${slash || ""}${search}`, { type: "docked" });
        Object.assign(window, { appContainerManager });
    }, [app, slash, search, appContainerManager]);

    useEffect(
        () =>
            autorun(() => {
                if (appContainerManager.lastFocusedDockedContainer) {
                    const url = `/${language.language}/${appContainerManager.lastFocusedDockedContainer.url}`;
                    if (url !== `${history.location.pathname}${history.location.search}`) {
                        history.push(url);
                    }
                }
            }),
        [appContainerManager.lastFocusedDockedContainer, history, language.language]
    );

    useEffect(() => {
        eventBus.on("drag_upload", (state: boolean) => {
            setDropState(state);
        });
        return () => {
            eventBus.removeListener("drag_upload", (state: boolean) => {
                setDropState(state);
            });
        };
    }, []);

    return (
        <Workbench>
            <Observer>
                {() => {
                    return (
                        <>
                            {appContainerManager.containers.map((container) => {
                                switch (container.type) {
                                    case "docked":
                                        return <DockedAppContainer key={container.id} container={container} />;
                                    default:
                                        return null;
                                }
                            })}
                        </>
                    );
                }}
            </Observer>
            {dropState ? <Upload activityContext={activityContext} /> : null}
        </Workbench>
    );
}
